//
//  PxRegViewController.m
//  OilCard
//
//  Created by Xu Yefeng on 14-5-18.
//  Copyright (c) 2014年 Free. All rights reserved.
//

#import "PxRegViewController.h"
#import "LL360CountDownButton.h"
#import "PxFormValidate.h"

@interface PxRegViewController ()

@end

@implementation PxRegViewController {
    NSString *belongStore;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    [self setLeftBack];
    // Do any additional setup after loading the view.
    [self setLogoTitleViewWithTitle:@"注册"];
    
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scroll.top = [PxGlobal getBaseHeight:NO];
//    scroll.backgroundColor = [UIColor redColor];
    [self.view addSubview:scroll];
    self.contentView = scroll;
    
    UIView *blankview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 15)];
    blankview.backgroundColor = [UIColor colorWithHTMLStr:@"f8f8f8"];
    [self.contentView addSubview:blankview];
    
    UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 1)];
    [self.contentView addSubview:lineview];
    lineview.top = blankview.bottom-1;
    lineview.backgroundColor = [UIColor colorWithHTMLStr:@"cacaca"];

    
    self.mobileNo = [PxWidgetCreater getTextField:@"手机号" andPlacehoder:@"请输入手机号"];
    self.mobileNo.clearButtonMode = UITextFieldViewModeWhileEditing;
//    self.mobileNo.text = @"13588116446";
    self.mobileNo.top = blankview.bottom;
    self.mobileNo.keyboardType = UIKeyboardTypeNumberPad;
    self.mobileNo.delegate = self;
    self.mobileNo.width = self.view.width - 100;
    [scroll addSubview:self.mobileNo];
    
    LLSmallCountDownButton *countdownBtn = [LLSmallCountDownButton countDownButtonWithTimerKey:@"register"];
    [countdownBtn stop];
    [self.contentView addSubview:countdownBtn];
    countdownBtn.frame = CGRectMake(self.mobileNo.right, self.mobileNo.top, 85, self.mobileNo.height);
    countdownBtn.backgroundColor = [UIColor colorWithHTMLStr:@"2c75c7"];
    [countdownBtn setSelector:@selector(sendVerify) withTarget:self];
    
    
    lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 1)];
    [self.contentView addSubview:lineview];
    lineview.top = self.mobileNo.bottom-1;
    lineview.backgroundColor = [UIColor colorWithHTMLStr:@"cacaca"];

    
    self.verifyCode = [PxWidgetCreater getTextField:@"验证码" andPlacehoder:@"请输入验证码"];
    self.verifyCode.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.verifyCode.keyboardType = UIKeyboardTypeNumberPad;
//    self.certificateNo.text = @"330326198812161111";
    self.verifyCode.top = self.mobileNo.bottom;
    self.verifyCode.delegate = self;
    [self.verifyCode linkPreField:self.mobileNo];
    self.verifyCode.width = self.view.width - 30;
    [scroll addSubview:self.verifyCode];
    
    lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 1)];
    [self.contentView addSubview:lineview];
    lineview.top = self.verifyCode.bottom-1;
    lineview.backgroundColor = [UIColor colorWithHTMLStr:@"cacaca"];

    
    self.password = [PxWidgetCreater getTextField:@"密码" andPlacehoder:@"请输入密码"];
    self.password.clearButtonMode = UITextFieldViewModeWhileEditing;
//    self.password.text = @"123456";
    self.password.top = self.verifyCode.bottom;
    self.password.delegate = self;
    self.password.secureTextEntry = YES;
    [self.password linkPreField:self.verifyCode];
    self.password.width = self.view.width - 30;
    [scroll addSubview:self.password];
    
    lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 1)];
    [self.contentView addSubview:lineview];
    lineview.top = self.password.bottom-1;
    lineview.backgroundColor = [UIColor colorWithHTMLStr:@"cacaca"];
    
    self.passwordCfm = [PxWidgetCreater getTextField:@"确认密码" andPlacehoder:@"请确认密码"];
    self.passwordCfm.clearButtonMode = UITextFieldViewModeWhileEditing;
//    self.passwordCfm.text = @"123456";
    self.passwordCfm.top = self.password.bottom;
    self.passwordCfm.delegate = self;
    self.passwordCfm.secureTextEntry = YES;
    [self.passwordCfm linkPreField:self.password];
    self.passwordCfm.width = self.view.width - 30;
    [scroll addSubview:self.passwordCfm];
    
//    UIButton *checkbox = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.checkBox = checkbox;
//    [checkbox.layer setMasksToBounds:YES];
//    [checkbox.layer setBorderWidth:1.0]; //边框宽度
//    [checkbox.layer setBorderColor:[UIColor colorWithHTMLStr:@"cacaca"].CGColor];
//    CGRect checkboxRect = CGRectMake(scroll.width/2-65,self.passwordCfm.bottom + 8,15,15);
//    [checkbox setFrame:checkboxRect];
////    [checkbox setImage:[UIImage imageNamed:@"checkbox_off.png"] forState:UIControlStateNormal];
//    [checkbox setImage:[UIImage imageNamed:@"Images/icon-selectRight"] forState:UIControlStateSelected];
//    [checkbox addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside];
//    [scroll addSubview:checkbox];
//    
//    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"《用户协议》"];
//    NSRange strRange = {0,[str length]};
//    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHTMLStr:@"3e71e7"] range:strRange];  //设置颜色
//    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
//
//    UIButton *xieyi = [[UIButton alloc] initWithFrame:CGRectMake(checkbox.right, checkbox.top,100,checkbox.height)];
//    [xieyi addTarget:self action:@selector(gotoXieYi) forControlEvents:UIControlEventTouchUpInside];
//    [scroll addSubview:xieyi];
//    [[xieyi titleLabel] setFont:[UIFont systemFontOfSize:12]];
//    [xieyi setAttributedTitle:str forState:UIControlStateNormal];

    
    
    
    lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 1)];
    [self.contentView addSubview:lineview];
    lineview.top = self.passwordCfm.bottom-1;
    lineview.backgroundColor = [UIColor colorWithHTMLStr:@"cacaca"];
    
    CGRect frame = CGRectMake(15, lineview.bottom, self.view.width - 30, 45);
    _selectLabel = [[PxClientSelectLabel alloc] initWithFrame:frame AndDelegate:self];
    NSMutableArray *arr = [PxGlobal getData:STORE_INFO];
    _selectLabel.pickerArray = arr;
    [self.contentView addSubview:_selectLabel];
    [_selectLabel setData:0];
    belongStore = arr[0][@"value"];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44.5)];
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = [UIColor colorWithHTMLStr:@"484848"];
    label.text = @"门店";
    
    _selectLabel.leftView = label;
    _selectLabel.textColor = [UIColor colorWithHTMLStr:@"333333"];
    _selectLabel.textAlignment = NSTextAlignmentRight;
    
    _selectLabel.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@""
                                                                  attributes:@{
                                                                               NSForegroundColorAttributeName: [UIColor colorWithHTMLStr:@"999999"],
                                                                               NSFontAttributeName : [UIFont systemFontOfSize:15]
                                                                               }
                                   ];
    
    UIView *line = [PxGlobal duplicate:lineview];
    line.top = _selectLabel.bottom-1;
    [self.contentView addSubview:line];
    
    UIButton *btn = [PxWidgetCreater customerButton];
    [btn setTitle:@"立即注册"];
    [btn setSelector:@selector(gotoRegister) withTarget:self];
    [btn setTitleColor:[UIColor colorWithHTMLStr:@"2f86e9"] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:18];
    btn.layer.borderColor = [UIColor colorWithHTMLStr:@"2f86e9"].CGColor;
    btn.layer.borderWidth = 1;
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 4;
    [self.contentView addSubview:btn];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.contentView).offset(-70);
        make.top.equalTo(line.mas_bottom).with.offset(20);
        make.height.equalTo(self.mobileNo);
        make.left.offset(35);
    }];
    
    scroll.contentSize = CGSizeMake(scroll.width, btn.bottom);
}

-(void)didSelectIndex:(NSInteger)row
{
    NSDictionary *data = _selectLabel.pickerArray[row];
    belongStore = data[@"value"];
}

-(void)gotoXieYi
{
//    [self pushViewController:@"PxWebViewController" withIncomingParam:@{@"name":@"用户协议",
//                                                                        @"url":[NSString stringWithFormat:@"%@/static/word/userRegisterProtocol.htm", WEB_HOME]
//                                                                        }];
}

-(void)checkboxClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.contentView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (BOOL)passwordCheck
{
    NSString *password = [self.password.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSString *passwordCfm = [self.passwordCfm.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if ([password isEqualToString:passwordCfm]) {
        return YES;
    }
    
    [self showMSG:@"两次输入的密码不匹配" withType:0];
    
    return NO;
}

- (void)gotoRegister
{
    if (![self isEmpty:self.contentView.subviews]) {
        if ([self passwordCheck]) {
            if (![[PxFormValidate sharedInstance] checkPhone:self.mobileNo.text])
                [self showMSG:@"请输入正确手机号" withType:0];
            else {
//                if (!self.checkBox.selected)
//                    [self showMSG:@"请确认用户协议" withType:0];
//                else
                    [self registerUser];
            }
        }
    }
}

- (void)registerUser
{
    NSString *password = [self.password.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSString *mobile = [self.mobileNo.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSString *verifyCode = [self.verifyCode.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    
    cmd.functionName = TRANS_USER_REGISTER;
    [cmd.paramDic addEntriesFromDictionary:@{@"belongStore":belongStore,
                                             @"employeeType":@"1",
                                             @"phone":mobile,
                                             @"password":password,
                                             @"code":verifyCode}];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        PxUserInfoBean *bean = [[PxUserInfoBean alloc] init];
        bean.loginName = mobile;
        bean.phone = mobile;
        [PxNetSession sharedSession].currentUser = bean;
        [LLAlertService alertWithTip:@"注册成功"];
//        [self pushRootViewController:@"PxHomeViewController" withIncomingParam:nil];
        [self popToLastControllerWithIncomingParam:nil];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [self showMSG:dic[RESULT_DESC] withType:1];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    [LLRestEngine sendCommandRequest:cmd];
}

- (void)sendVerify{
    LLSmallCountDownButton *countdownBtn = [LLSmallCountDownButton countDownButtonWithTimerKey:@"register"];
    
    if (nil == self.mobileNo.text || 0 == self.mobileNo.text.length) {
        [self showMSG:@"请输入手机号" withType:0];

        return;
    }
    
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_USER_SMS_SEND;
    [cmd.paramDic addEntriesFromDictionary:@{@"phone":self.mobileNo.text,
                                             @"loginName":self.mobileNo.text,
                                             @"type":@"r"
                                             }];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:@"验证码已发送，请查收"];
        [countdownBtn start];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:dic[RESULT_DESC]];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    [LLRestEngine sendCommandRequest:cmd];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
//    self.contentView.contentSize = CGSizeMake(self.contentView.width,self.contentView.height + 216);//原始滑动距离增加键盘高度
    
    CGPoint pt = [textField convertPoint:CGPointZero toView:self.contentView];//把当前的textField的坐标映射到scrollview上
    if(self.contentView.contentOffset.y-pt.y+80<=0)//判断最上面不要去滚动
        [self.contentView setContentOffset:CGPointMake(0, pt.y-80) animated:YES];
}

//- (BOOL)textFieldShouldReturn:(UITextField*)theTextField
//{
//    //开始动画
//    [UIView beginAnimations:nil context:nil];
//    //设定动画持续时间
//    [UIView setAnimationDuration:0.3];
//
//    self.contentView.contentSize = CGSizeMake(self.contentView.width, self.passwordCfm.bottom + 5);
//    
//    self.contentView.contentSize = CGSizeMake(self.contentView.width,self.contentView.height - 216);
//    //动画结束
//    [UIView commitAnimations];
//    
//    return YES;
//}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
//    //开始动画
//    [UIView beginAnimations:nil context:nil];
//    //设定动画持续时间
//    [UIView setAnimationDuration:0.3];
//    
//    self.contentView.contentSize = CGSizeMake(self.contentView.width, self.passwordCfm.bottom + 5);
//    
//    self.contentView.contentSize = CGSizeMake(self.contentView.width,self.contentView.height - 216);
//    //动画结束
//    [UIView commitAnimations];
    
//    if (textField == self.mobileNo) {
//        [self checkUserAvailable];
//    }
}

- (void)checkUserAvailable{
    NSString *mobileNo = [self.mobileNo.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.useSystemHold = NO;
    
    cmd.functionName = TRANS_USER_CHECK;
    [cmd.paramDic addEntriesFromDictionary:@{@"loginName":mobileNo}];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:dic[@"RESPONSECONTENT"]];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    [LLRestEngine sendCommandRequest:cmd];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    LLSmallCountDownButton *countDownBtn = [LLSmallCountDownButton countDownButtonWithTimerKey:@"register"];
    [countDownBtn removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
}

@end
